<template lang="pug">
  .tobanScheduleWrapper
    el-row(:gutter="12")
      el-col(:span="16")
        form-box(
        ref="form"
        :fields="items"
        :baseData="{ weekDay }"
        isFilter
        :showBtns="false"
        :enabled="addType"
        )
      el-col.tr(:span="8")
        .btnGroup
          el-button.gradientVertical(
            v-show="addType"
            size="large"
          ) 排课学生 {{addChildren.name || ''}}
          el-button.gradientVertical(
            v-show="addType"
            size="large"
            @click="selectTeacher"
          ) 授课老师 {{addTeacher.realName || ''}}
          el-button.gradientVertical(type="primary" size="large" round @click="selectChildren" v-show="!addType") 新增
    el-tabs.dateTtab(v-model="weekDayValue" stretch)
      el-tab-pane(v-for="day in weekDays" :key="day" :name="day" :label="day")
    div(v-loading="loading")
      empty(v-if="nurseryScheduleRecordList.length < 1 && !canSchedule" title="暂无排课")
      toban-item(
        ref="tobanItem"
        v-for="(item, index) in nurseryScheduleRecordList"
        :key="item.id"
        :list="nurseryScheduleRecordList"
        :value="item"
        :show="true"
        :canSchedule="canSchedule && addType"
        :indexInList="index"
        @delHandle="delSchedule"
        @selectCourse="selectCourse"
        @saveSchedule="saveSchedule"
      )
      toban-item(
        v-if="addVisible"
        ref="tobanItemAdd"
        :show="true"
        :isAdd="true"
        :list="nurseryScheduleRecordList"
        @selectCourse="selectCourse"
        @saveSchedule="saveSchedule"
      )
      p.addTxt.tc(v-if="canSchedule && addType")
        a(javascript="javascript:void(0)" @click="() => addToggle(true)")
          i.iconfont.icon-020tianjia.mr5
          | 添加
      p.tr.mt20
        <!--el-button(size="large" type="success" v-if="canSchedule" @click="autoSchedule" :loading="autoSubmitting" round plain) 自动排课-->
        el-button.gradientVertical(size="large" v-if="canSchedule" @click="cancelHandle" :loading="submitting" round v-show="addType") 取消
        el-button.gradientVertical(size="large" v-if="canSchedule" @click="submitHandle" :loading="submitting" round v-show="addType") 保存
    //- 课程选择
    course-selector(
      v-model="courseSelectObj.visible"
      :initCourse.sync="courseSelectObj.course"
      packageType="1"
      @sureHandle="saveSchedule"
    )
    children-selector(
      :visible.sync="childrenVisible"
      @sureHandle="childrenSureHandle"
    )
    teacher-selector(
      :visible.sync="teacherVisible"
      @sureHandle="teacherSureHandle"
    )
</template>
<script>
import dayjs from 'dayjs'
import Empty from '@/components/Basic/Empty'
import Alert from '@/components/Basic/Alert'
import { getDateFromWeek } from '@/utils/date'
import { sortByProperty } from '@/utils/util'
import { getDoor2DoorChildren, getSchedulerDetail, nurserySchuleSubmit } from '../api'
import TobanItem from '../components/tobanItem'
import CourseSelector from '../components/courseSelector'
import { mapGetters } from 'vuex'
import ChildrenSelector from '@/components/Business/ChildrenSelector'
import TeacherSelector from '@/components/Business/TeacherSelector'
const dateFormatStr = 'YYYY/MM/DD'
import { isEmpty } from '@/utils/util'
const warnStrs = [
  '请逐项添加详细的托班一日生活流程!',
  '本周课表已审核通过，不支持修改!',
  '本周课表正在审核中，暂时不能修改哦~',
  '当前日期已过，不支持排课！'
]

const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

const initDay = new Date().getDay()

export default {
  components: {
    Empty,
    Alert,
    TobanItem,
    CourseSelector,
    ChildrenSelector,
    TeacherSelector
  },
  data () {
    return {
      loading: false,
      submitting: false,
      addVisible: false, // 是否显示新增项
      autoSubmitting: false, // 自动排课按钮submitting
      checkSubmitting: false, // 提交审核submitting
      weekDays, // 周列表
      weekDayValue: weekDays[initDay === 0 ? 6 : initDay - 1], // 周几
      nurseryScheduleId: '', // 当前日期的排课id
      nurseryScheduleRecordList: [], // 当前日期的排课列表
      checkInfo: null, // 审核详情
      courseSelectObj: {
        visible: false,
        course: null
      }, // 选择课程

      childrenList: [],
      childrenId: '',

      weekDay: new Date(), // 排课日期
      tplObj: {
        visible: false
      },

      addType: false,
      childrenVisible: false,
      addChildren: {},

      teacherVisible: false,
      addTeacher: {}
    }
  },
  computed: {
    ...mapGetters(['curArea']),
    weekDuration () {
      return getDateFromWeek(this.weekDay)
    },
    curDateStr () {
      const { weekDay } = this
      return dayjs(weekDay).format(dateFormatStr)
    },
    // 当前是否支持排课
    canSchedule () {
      const { weekDay, checkInfo, isChecking } = this
      return checkInfo?.status !== 1 && !isChecking && weekDay.getTime() >= new Date(dayjs().format(dateFormatStr)).getTime()
    },
    // 排课提示语
    warnText () {
      const { weekDay, checkInfo, isChecking } = this
      if (checkInfo?.status === 1) {
        return warnStrs[1]
      }
      if (isChecking) {
        return warnStrs[2]
      }
      if (weekDay.getTime() < new Date().getTime() - 24 * 3600 * 1000) {
        return warnStrs[3]
      }
      return warnStrs[0]
    },
    isChecking () {
      const { checkInfo } = this
      return checkInfo && checkInfo.status !== 2
    },
    items () {
      const { childrenId, weekDay, addType } = this
      return [
        {
          key: 'childrenId',
          type: 'select',
          initialValue: childrenId,
          fieldProps: {
            placeholder: '学生选择',
            options: this.childrenList,
            props: { value: 'id', label: 'name' },
            disabled: addType
          },
          events: {
            change: val => this.searchFormChange(val, 'childrenId')
          }
        },
        {
          key: 'weekDay',
          type: 'week',
          initialValue: weekDay,
          fieldProps: {
            pickerOptions: { firstDayOfWeek: 1 },
            format: 'yyyy 第 WW 周',
            placeholder: '时间选择',
            disabled: addType
          },
          events: {
            change: val => this.searchFormChange(val, 'weekDay')
          }
        }
      ]
    }
  },
  watch: {
    // 获取详情监听
    weekDay () {
      this.getInfo()
    },
    childrenId () {
      this.getInfo()
    },
    // 周几变化了，日期也要变化
    weekDayValue (val) {
      const { weekDuration } = this
      this.weekDay = new Date(weekDuration.dateArr[weekDays.indexOf(val)])
    },
    // 周变化之后重新获取审核信息
    'weekDuration.startDateString': {
      handler (val) {
        this.getCheck()
      }
    }
  },
  created () {
    this.getChildren()
  },
  methods: {
    addCourse () {
      this.addChildren = {}
      this.addTeacher = {}
      this.addType = true
    },
    cancelHandle () {
      this.addType = false
      this.getInfo()
    },
    // 获取排课详情
    getInfo () {
      let { childrenId } = this
      const { curDateStr } = this
      if (this.addType) {
        childrenId = this.addChildren.id
      }
      if (isEmpty(childrenId)) {
        this.nurseryScheduleId = ''
        this.nurseryScheduleRecordList = []
        return
      }
      this.loading = true
      getSchedulerDetail({ childrenId, courseDateStr: curDateStr }).then(res => {
        this.addToggle(false)
        this.nurseryScheduleId = res?.nurseryScheduleId
        this.nurseryScheduleRecordList = res?.nurseryScheduleRecordList || []
      }).finally(() => {
        this.loading = false
      })
    },
    // 搜索栏form表单
    searchFormChange (val, key) {
      this[key] = val
      if (key === 'weekDay') {
        this.weekDayValue = weekDays[val.getDay() - 1]
      } else if (key === 'childrenId') {
        this.childrenId = val
      }
    },
    async getChildren () {
      const data = await getDoor2DoorChildren()
      this.childrenList = data
      if (isEmpty(this.childrenId)) {
        this.childrenId = this.childrenList[0]?.id || ''
      }
    },
    // 添加课程
    addToggle (flag = false) {
      this.addVisible = flag
    },
    // 删除排课
    delSchedule (id) {
      const { nurseryScheduleRecordList } = this
      this.nurseryScheduleRecordList = nurseryScheduleRecordList.filter(x => x.id !== id)
    },
    // 选择课程
    selectCourse (item) {
      console.log(item)
      this.courseSelectObj = {
        visible: true,
        course: item
      }
    },
    // 排课，flag-新增
    saveSchedule (item, flag) {
      this.addToggle(false)
      const { curDateStr } = this
      let list = this.nurseryScheduleRecordList
      console.log(item, flag)
      if (!flag) {
        list = list.map(x => {
          if (x.id === item.id) {
            x = item
          }
          return x
        })
        const tobanItemRefs = this.$refs.tobanItem
        tobanItemRefs.map(ref => {
          ref.editHandle(false, false)
        })
      } else {
        const tobanItemAddRef = this.$refs.tobanItemAdd
        tobanItemAddRef.course = {
          remark: '',
          timeRange: [new Date('1990-01-01 8:00:00'), new Date('1990-01-01 18:00:00')]
        }
        list.push(item)
      }
      list.map(x => {
        x.beginDate = new Date(curDateStr + ' ' + x.begin).getTime()
        x.endDate = new Date(curDateStr + ' ' + x.end).getTime()
        return x
      })
      this.nurseryScheduleRecordList = list.sort(sortByProperty('begin', 'time'))
    },

    // 保存排课
    submitHandle () {
      if (isEmpty(this.addChildren.id)) {
        this.$message('请先选择排课学生')
        return
      }
      if (isEmpty(this.addTeacher.id)) {
        this.$message('请先选择排课老师')
        return
      }
      const { curDateStr, nurseryScheduleRecordList } = this
      const addChildrenId = this.addChildren.id
      const addTeacherId = this.addTeacher.id
      // console.log(nurseryScheduleRecordList)
      const params = {
        scheduleJson: JSON.stringify(nurseryScheduleRecordList.map(x => {
          const { isAdd, id, activityContent, begin, end, category, resObj, remark } = x
          const obj = {
            activityContent,
            begin,
            end,
            category: Number(category),
            resObj,
            remark
          }
          if (isAdd) {
            return obj
          } else {
            return {
              id,
              beginDate: new Date(curDateStr + ' ' + begin).getTime(),
              endDate: new Date(curDateStr + ' ' + end).getTime(),
              ...obj
            }
          }
        }))
      }
      // if (nurseryScheduleId) {
      //   params.nurseryScheduleId = nurseryScheduleId
      //   params.childrenId = addChildrenId
      //   params.teacherId = addTeacherId
      // } else {
      //   params.childrenId = addChildrenId
      //   params.teacherId = addTeacherId
      //   params.lessonDate = curDateStr
      // }
      params.childrenId = addChildrenId
      params.teacherId = addTeacherId
      params.lessonDate = curDateStr

      this.submitting = true
      console.log(params)
      nurserySchuleSubmit(params, 'add').then(res => {
        if (res) {
          this.childrenId = addChildrenId
          this.addType = false
          this.getChildren()
          this.getInfo()
        }
      }).finally(() => {
        this.submitting = false
      })
    },

    selectChildren () {
      this.childrenVisible = true
    },

    childrenSureHandle (data) {
      console.log(data)
      this.addType = true
      this.addChildren = data[0]
      this.getInfo()
    },

    selectTeacher () {
      this.teacherVisible = true
    },

    teacherSureHandle (data) {
      console.log(data)
      this.addTeacher = data[0]
    }
  }
}
</script>
<style lang="scss" scoped>

  .tobanScheduleWrapper {
    > .header{
      display: flex;
      align-items: center;
      margin-bottom: 16px;

      > h2 {
        font-size: 16px;
        margin-right: 12px
      }
    }
  }

  .btnGroup{
    /*position: absolute;*/
    /*right: 0;*/
    /*top: 0*/
  }

  .dateTtab{
    ::v-deep {
      > .el-tabs__header{
        margin-bottom: 0
      }
      .el-tabs__item{
        padding: 0;
        height: 66px;
        line-height: 66px;
        background: #FAFAFA;
        font-size: 17px;
        font-family: PingFang SC;
      ;
        color: #6E645A;
        position: relative;

        &::before{
          content: '';
          display: block;
          height: 1px;
          position: absolute;
          left: 0;
          right: 0;
          top: 0;
          background: #E8E8E8;
          z-index: 5;
        }

        &.is-active, &:hover{
          color: #333333;

          &::before{
            height: 5px;
            background: linear-gradient(90deg, $--app-linear-gradient-stop1 0%, $--app-linear-gradient-stop2 100%);
          }
        }
      }

      .el-tabs__nav-wrap::after, .el-tabs__active-bar{
        display: none;
      }
    }
  }

  .el-tabs__nav{}

  .weekWrapper{
    position: relative;

    .weekStr {
      position: relative;
      z-index: 0;
    }
    .weekInput{
      position: absolute;
      z-index: 10;
      width: 100%;
      height: 100%;
      opacity: 0;
      left: 0;
      top: 0;
      bottom: 0;
      right: 0
    }
  }

  .el-divider--horizontal{
    margin-top: 36px
  }

  .addTxt{
    font-size: 15px;
    font-family: PingFang SC;
    color: #999999;
    padding: 32px 0;
    border-bottom: 1px dashed #E8E8E8;

    i {
      font-size: 20px;
      vertical-align: middle;
    }
  }
</style>
